package com.bocloud.cmp.driver.providers.ali;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.ecs.model.v20140526.CreateSecurityGroupRequest;
import com.aliyuncs.ecs.model.v20140526.CreateSecurityGroupResponse;
import com.aliyuncs.ecs.model.v20140526.DeleteSecurityGroupRequest;
import com.aliyuncs.ecs.model.v20140526.DeleteSecurityGroupResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeSecurityGroupsRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeSecurityGroupsResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeSecurityGroupsResponse.SecurityGroup;
import com.aliyuncs.exceptions.ClientException;
import com.bocloud.cmp.driver.providers.SecurityGroupDriver;
import com.bocloud.cmp.model.SecurityGroupModel;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.utils.DateTools;
import com.google.common.collect.Lists;

public class AliSecurityGroupDriver extends AliDriver implements SecurityGroupDriver {

	private static final int PAGE_SIZE = 50;
	private static Logger logger = LoggerFactory.getLogger(AliSecurityGroupDriver.class);

	public AliSecurityGroupDriver() {
		super();
	}

	public AliSecurityGroupDriver(String accessKey, String secretKey, String regionId) {
		super(accessKey, secretKey, regionId);
	}

	@Override
	public BsmResult list() {
		DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
		request.setPageNumber(1);
		request.setPageSize(PAGE_SIZE);
		List<SecurityGroupModel> models = Lists.newArrayList();
		try {
			DescribeSecurityGroupsResponse response = this.getClient().getAcsResponse(request);
			List<SecurityGroup> groups = response.getSecurityGroups();
			int totalCount = response.getTotalCount();
			for (SecurityGroup group : groups) {
				models.add(this.convert(group));
			}
			int totalPage = totalCount / PAGE_SIZE + 1;
			if (totalPage == 1) {
				return new BsmResult(true, models, "success");
			}
			for (int i = 2; i <= totalPage; i++) {
				request.setPageNumber(i);
				request.setPageSize(PAGE_SIZE);
				response = this.getClient().getAcsResponse(request);
				groups = response.getSecurityGroups();
				for (SecurityGroup group : groups) {
					models.add(this.convert(group));
				}
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException e) {
			logger.error("list security group error:", e);
			return new BsmResult(false, e.getErrCode(), e.getErrMsg());
		}

	}

	@Override
	public BsmResult create(SecurityGroupModel group) {
		CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();
		request.setDescription(group.getRemark());
		request.setSecurityGroupName(group.getName());
		request.setVpcId(null);
		try {
			CreateSecurityGroupResponse response = this.getClient().getAcsResponse(request);
			return detail(response.getSecurityGroupId());
		} catch (ClientException e) {
			logger.error("create secuurity [{}] error", JSONObject.toJSONString(group), e);
			return new BsmResult(false, e.getErrCode(), e.getErrMsg());
		}
	}

	@Override
	public BsmResult remove(String sgId) {
		DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest();
		request.setSecurityGroupId(sgId);
		try {
			DeleteSecurityGroupResponse response = this.getClient().getAcsResponse(request);
			return new BsmResult(true, response.getRequestId(), response.getRequestId());
		} catch (ClientException e) {
			logger.error("remove secuurity [{}] error", JSONObject.toJSONString(sgId), e);
			return new BsmResult(false, e.getErrCode(), e.getErrMsg());
		}
	}

	@Override
	public BsmResult detail(String sgId) {
		SecurityGroupModel model = null;
		BsmResult result = this.list();
		if (result.isSuccess()) {
			@SuppressWarnings("unchecked")
			List<SecurityGroupModel> groups = (List<SecurityGroupModel>) result.getData();
			for (SecurityGroupModel group : groups) {
				if (group.getUuid().equals(sgId)) {
					model = group;
					break;
				}
			}
		}
		if (null == model) {
			return new BsmResult(false, "get securitygroup detail error");
		} else {
			return new BsmResult(true, model, "success");
		}
	}

	private SecurityGroupModel convert(SecurityGroup group) {
		if (null == group) {
			return null;
		}
		SecurityGroupModel model = new SecurityGroupModel();
		model.setGmtCreate(DateTools.transfer("yyyy-MM-dd'T'HH:mm:ssZ", group.getCreationTime(), "Z"));
		model.setName(group.getSecurityGroupName());
		model.setRemark(group.getDescription());
		model.setUuid(group.getSecurityGroupId());
		return model;
	}

}
